<template>
  <div class="checkbox-group-wrapper">
    <el-checkbox-group v-model="exitCheckList">
      <el-checkbox
        :disabled="customGroupState"
        v-for="(item, index) in editorData"
        :label="item"
        :key="item.name">{{item.name}}</el-checkbox>
      <div class="tips" v-if="isShowTips">{{tips}}</div>
      <base-group class="custom-group-wrapper"
        v-if="customState"
        :value="customGroupValue"
        :disabled="customGroupState"
        :simple-layout="true"
        :max-item="MAX_CUSTOM_GROUP_NUM"
        @add="handleCustomCheckAdd"
        @remove="handleCustomCheckRemove">
        <template scope="scope">
          <x-checkbox
            v-bind="$props"
            :disabled="customGroupState"
            :formType="formType"
            :value="scope.item"
            :index="scope.index"
            :exitCheckList="exitCheckList"
            :exitNameList.sync="exitNameList"
            @change="handleCustomCheckChange"/>
        </template>
      </base-group>
    </el-checkbox-group>
  </div>
</template>
<script>
  import XCheckbox from './XCheckbox'
  import BaseGroup from '@/modules/components/BaseGroup'
  import * as ui from 'l-element'
  import { cloneObj } from 'utils'

  import serviceApi from 'api/service'
  import {
    FORM_TYPE_ENUMS,
    DATA_TYPE_ENUMS,
    SALE_CUSTOM_CHECK,
    MAX_CUSTOM_GROUP_NUM
  } from '../constant'
  export default {
    components: {
      BaseGroup,
      XCheckbox
    },
    mixins: [],
    props: {
      ...ui.default.Input.props, // 继承Input的所有属性
      minlength: {
        type: Number
      },
      maxlength: {
        type: Number
      },
      isTrain: {
        type: Boolean
      },
      value: Array,
      data: Object,
      index: Number,
      min: Number,
      editorType: String,
      customGroupState: Boolean,
      groupLen: Number // 组别个数
    },
    computed: {
      formType () {
        // 当前只做文本框和单时间输入框
        let showModel = this.data ? this.data.showModel : FORM_TYPE_ENUMS.INPUT
        showModel = showModel === FORM_TYPE_ENUMS.TIME ? FORM_TYPE_ENUMS.TIME : FORM_TYPE_ENUMS.INPUT
        return showModel
      }
    },
    watch: {
      exitCheckList: '_getDiffInArray',
      editorData () {
        if (!this.exitNameList.length) {
          this.exitNameList = this.editorData.map(k => k.name)
        }
      }
    },
    created () {
      // window.tyler1 = this
      // 编辑状态下  如果不是跑步 则禁用修改
      this.initData() // 初始化组别数据
    },
    mouted () {
      // 初始化自定义组别  同时也在这里判断是否显示自定义
      this.customGroupValue.push(cloneObj(SALE_CUSTOM_CHECK))
    },
    data () {
      return {
        editorData: this.value,
        isShowTips: !1,
        tips: `暂无${this.data.attrName}，请先设置`,
        customGroupValue: [], // 自定义组别
        exitNameList: [],
        exitCheckList: [],
        newAddCheckList: [],
        isFirst: !0, // 是否第一次加载
        customState: !0, // 是否可自定义
        MAX_CUSTOM_GROUP_NUM: MAX_CUSTOM_GROUP_NUM // 自定义组别个数
      }
    },
    methods: {
      initData () {
        /**
         * 数据类型 1-url 2-text 3-json
         * 1、一般为下拉框需要通过url获取数据
         * 2、一般为文本框
         * 3、一般为多选框
         */
        let type = this.data.dataType - 0
        let attrValue = this.data.attrValue
        let jsonData = {}
        switch (type) {
          case DATA_TYPE_ENUMS.URL:
            jsonData = JSON.parse(attrValue)
            this.getItemData(jsonData)
            break
          case DATA_TYPE_ENUMS.TEXT:
            // 销售属性 这种情况暂时不会有
            // this.$message({
            //   message: `数据格式错误，请联系客服处理`,
            //   type: 'error'
            // })
            this.setItemData({data: []})
            // this.editorData = attrValue
            // this.editorState = !0
            break
          case DATA_TYPE_ENUMS.JSON:
            jsonData = JSON.parse(attrValue)
            this.setItemData(jsonData)
            break
          default:
            this.editorData = attrValue
        }
      },
      _getDiffInArray (newArr, oldArr, type) {
        let _newArr = newArr // 存储临时数据
        let changeType = newArr.length > oldArr.length ? 'plus' : 'reduce'
        let diffItem = []
        if (!oldArr.length) {
          diffItem = newArr
        } else {
          if (newArr.length > oldArr.length) {
            // d
          } else {
            [newArr, oldArr] = [oldArr, newArr]
          }
          newArr.forEach(newItem => {
            if (!oldArr.includes(newItem)) {
              diffItem.push(newItem)
            }
          })
        }
        // 合并 多组别 和 单组别的处理方法
        this.$emit('input', _newArr)
        this.$emit('change', {
          isFirst: this.isFirst,
          type: changeType,
          item: diffItem,
          items: _newArr,
          index: this.index
        })
        this.isFirst = !1
      },
      getItemData (config) {
        serviceApi.dict(config.url).then(({data}) => {
          // 请求完成 启用编辑模式
          // this.editorState = !0
          config.data = data
          this.setItemData(config)
        })
      },
      setItemData ({data = [], text, value, custom}) {
        this.customState = custom === 0 || custom === '0' ? !1 : !0 // custom为0 表示不允许自定义组别
        if (!data.length) {
          // 不能自定义的 无数据的提示
          if (!this.customState) {
            this.isShowTips = !0
          }
          // 培训特殊提示
          if (this.isTrain) {
            this.$message({
              message: '发布培训课程需先设置校区，请去校区管理添加',
              type: 'warning'
            })
          }
        }
        this.editorData = data.map(item => {
          return {
            ...item,
            custom: 0, // 非自定义
            skuCode: `${this.data.attrCode}_${item[value]}`, // 多组别时用来获取库存数据
            name: item[text], // url模式下 JSON对象的text为数据的name_key
            value: item[value] // url模式下 JSON对象的value为数据的value_key
          }
        })
        let newArr = []
        let {editorValues = []} = this.data
        this.editorData.forEach((item, index) => {
          // debugger
          if (this.editorType) {
            let delIndex = -1
            let editItem = editorValues.find((k, kIndex) => {
              let flag = Boolean(k.attrName === item.name)
              delIndex = flag ? kIndex : delIndex // 保存索引
              return flag
            })
            if (editItem) {
              item.price = editItem.price
              item.num = editItem.num
              item.linmitNum = editItem.linmitNum
              newArr.push(item)
              // 删除非自定义项  能找到这有索引
              editorValues.splice(delIndex, 1)
            }
          } else if (index < this.min) {
            newArr.push(item)
          }
        })
        // 编辑情况下 需要处理
        if (this.editorType) {
          this.customGroupValue = editorValues.length ? editorValues : [cloneObj(SALE_CUSTOM_CHECK)]
          // 添加自定义项
          editorValues.forEach(k => {
            k.name = k.attrName
            k.value = k.attrValue
            k.skuCode = `${this.data.attrCode}_${k.attrValue}` // 多组别时用来获取库存数据
            k.custom = 1 // 自定义
            k.key = this.unique()
            newArr.push(k)
          })
        } else {
          this.customGroupValue = [cloneObj(SALE_CUSTOM_CHECK)]
        }
        this.exitCheckList = newArr
      },
      handleCheckboxChange (index, data) {
        // debugger
        this.$set(this.customCheckArr, index, data)
      },
      handleAddCheckbox () {
        this.customCheckArr.push(cloneObj(SALE_CUSTOM_CHECK))
      },
      handleRemoveCheckbox (index) {
        this.customCheckArr.splice(index, 1)
      },
      handleCustomCheckAdd () {
        let newAddItem = cloneObj(SALE_CUSTOM_CHECK)
        newAddItem.key = this.unique()
        this.customGroupValue.push(newAddItem)
      },
      handleCustomCheckRemove (index) {
        let delItem = this.customGroupValue[index]
        this.customGroupValue.splice(index, 1) // 自定义组别删除
        this._deleteExitItem(delItem)
      },
      _deleteExitItem (item) {
        let delIndex = -1
        let newArr = this.exitCheckList.filter((k, kIndex) => {
          if (k.name !== item.name) {
            return true
          } else {
            delIndex = kIndex
            return false
          }
        })
        this._getDiffInArray(newArr, this.exitCheckList, 'noAutoChange')
        this.$nextTick(_ => {
          if (delIndex !== -1) {
            this.exitCheckList.splice(delIndex, 1)
          }
        })
        let exitIndex = item.nameIndex
        setTimeout(() => {
          if (!exitIndex || exitIndex === -1) {
            exitIndex = this.exitNameList.findIndex(k => k === item.name)
          }
          this.exitNameList.splice(exitIndex, 1)
        }, 200)
      },
      handleCustomCheckChange (index, newVal) {
        this.$set(this.customGroupValue, index, newVal)
      }
    }
  }
</script>
<style lang="scss">
  .checkbox-group-wrapper{
    .custom-group-wrapper{
      .base-group-item{
        display: inline-block;
        margin-bottom: 6px;
        &+ .base-group-item{
          margin-top:0;
        }
        .el-checkbox{
          margin-right: 0;
        }
      }
    }
    .tips{
      text-indent: 2em;
      color: #999;
    }
  }
</style>
